package ext.tianma.bom.service.rfq;

import java.io.File;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ext.com.core.CoreUtil;
import ext.tianma.bom.service.SelectPartService;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.PLMSynchronousPartService;
import ext.tianma.part.PartCommands;
import ext.tianma.util.PropertiesUtil;
import ext.workflow.WorkFlowUtil;
import wt.log4j.LogR;
import wt.mail.EMailMessage;
import wt.org.DirectoryContextProvider;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.pom.Transaction;
import wt.session.SessionServerHelper;
import wt.util.WTException;

public class RFQService {
	private static final Logger log = LogR.getLogger(RFQService.class.getName());

	/**
	 * 校验传入参数并创建成品
	 * 
	 * @param parts
	 * @param ibaValues
	 * @param rfqNum
	 * @param userCode
	 * @return
	 */
	public static String createFinishedPart(String parts, String ibaValues, String rfqNum, String userCode) {

		Hashtable<String, String> valuesAttr = new Hashtable<String, String>();
		List<String> numList = new ArrayList<String>();
		JSONObject object = new JSONObject();
		JSONArray erdpArr = new JSONArray();
		StringBuffer buffer = new StringBuffer();
		StringBuffer EmailBuffer = new StringBuffer();
		StringBuffer repartPartBuf = new StringBuffer();
		WTUser creator = null;

		boolean flagAccess = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction trx = new Transaction();
		try {
			trx.start();

			// 获取成品属性
			JSONObject obj = new JSONObject(ibaValues);
			Iterator<String> iter = obj.keys();
			while (iter.hasNext()) {
				// 获得key
				String key = iter.next();
				String value = obj.getString(key).trim();
				if (StringUtil.isNullOrEmpty(value)) {
					value = "";
				}
				valuesAttr.put(key, value);
			}

			// 判断rfq编号是否为空
			if (StringUtil.isNullOrEmpty(rfqNum)) {
				buffer.append("RFQ编号不能为空!");
			}
			valuesAttr.put("partRFQNumber", rfqNum);

			// 判断邮箱和成品编号、名称，得到要创建的成品编号和名称

			Hashtable<String, String> table = judge(parts, userCode, buffer, EmailBuffer, repartPartBuf, creator);
			String emessage = buffer.toString();
			String repbuf = repartPartBuf.toString();
			if (StringUtil.isNullOrEmpty(emessage) && table.size() != 0) {

				if (StringUtil.isNullOrEmpty(repbuf)) {

					List<WTPart> partList = createParts(table, valuesAttr, creator);

					for (int i = 0; i < partList.size(); i++) {
						JSONObject erdpObj = new JSONObject();
						WTPart part = partList.get(i);
						erdpObj.put("productName", part.getName());
						erdpObj.put("productNumber", part.getNumber());
						erdpObj.put("linkedReason", "创建数据");
						erdpObj.put("rfqNumber", rfqNum);
						erdpArr.put(erdpObj);
						numList.add(part.getNumber());
					}
					object.put("partNumber", numList.toString());// sucessArray
					object.put("status", "success");
					object.put("message", "成品创建成功！");
					//用户不存在用管理员创建不发送邮件
					if(!EmailBuffer.toString().equals("NoEmail")) {
						sendEmail(partList, EmailBuffer.toString());
					} 
					System.out.println("------不发送邮件 ---------");

				} else {
					// 成品编号重复
					object.put("partNumber", "");
					object.put("status", "success");
					object.put("message", repbuf);
				}

			} else {
				// 存在报错信息，直接输出
				object.put("partNumber", "");
				object.put("status", "failed");
				object.put("message", emessage);
			}

			trx.commit();
			trx = null;

			// 调用ERDP接口
			if (StringUtil.isNullOrEmpty(emessage) && table.size() != 0) {
				if (StringUtil.isNullOrEmpty(repbuf)) {
					sendToErdp(erdpArr);
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.info(e);
			log.info("================" + e);
			//e.printStackTrace();
		} finally {
			if (trx != null) {
				trx.rollback();
			}
			SessionServerHelper.manager.setAccessEnforced(flagAccess);
		}
		return object.toString();
	}

	// 创建成品
	public static List<WTPart> createParts(Hashtable<String, String> table, Hashtable<String, String> attr, WTUser creator) {
		List<WTPart> list = new ArrayList<WTPart>();
		if (table.size() != 0) {
			// 无错误信息，创建成品
			Enumeration<String> e = table.keys();
			try {
				while (e.hasMoreElements()) {
					String number = e.nextElement().trim();
					String name = table.get(number).trim();
					WTPart good = WTPart.newWTPart();

					good = PartCommands.createRFQFinishedGood(number, name, attr, null, creator);
					
					if(good != null) {
						list.add(good);
					}

				}
			} catch (Exception e1) {
				//e1.printStackTrace();
				log.info(e1);
				log.info("================" + e1);
			}
		}
		return list;
	}

	/**
	 * 向指定用户发送邮件通知
	 * 
	 * @param list
	 * @param email
	 */
	public static void sendEmail(List<WTPart> list, String email) {

		try {
			WTPart part = WTPart.newWTPart();
			String number = "";
			String name = "";
			String url = "";
			String infoPage = "";
			String emailAddr = email;
			String content = "";

			for (int i = 0; i < list.size(); i++) {
				part = list.get(i);
				// part = PartUtil.getWTPartByNumber(number);
				number = part.getNumber();
				name = part.getName();
				url = SelectPartService.generateInfoPageURL(part);
				infoPage = "<a target='_blank' href='" + url + "'>" + "点击查看详情" + "</a><br/>";

				content += "成品创建成功，成品编码为" + number + "，" + infoPage;
			}


			emailAddr += ";";
			// 邮件内容
			StringBuffer body = new StringBuffer();
			// String content = tempContent;
			body.append(content);

			String[] emailSendTo = emailAddr.split(";");// 邮箱拼接
			EMailMessage mail = EMailMessage.newEMailMessage();
			mail.addEmailAddress(emailSendTo);
			// 邮件主题
			StringBuffer title = new StringBuffer();
			title.append("成品创建成功");
			mail.setSubject(title.toString());
			mail.setMultipartSubtype("text/html;charset=\"UTF8\"");
			mail.addPart(body.toString(), "text/html;charset=\"UTF8\"");
			mail.send(false);

		} catch (WTException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.info(e);
			log.info("================" + e);
		}
	}

	/**
	 * 判断传入参数中成品编码是否重复以及员工编码是否有误
	 * 
	 * @param parts
	 * @param userCode
	 * @param buffer
	 * @param ebuffer
	 * @return
	 * @throws Exception
	 */
	public static Hashtable<String, String> judge(String parts, String userCode, StringBuffer buffer,
			StringBuffer ebuffer, StringBuffer repartPartBuf, WTUser creator) throws Exception {
		String num = "";
		String number = "";
		String name = "";
		Hashtable<String, String> table = new Hashtable<String, String>();
		// StringBuffer buffer = new StringBuffer();

		try {

			// 邮箱是否存在
			if (!StringUtil.isNullOrEmpty(userCode)) {
				// 根据用户名查找
				WTUser user1 = WorkFlowUtil.GetUserByName(userCode);
				// 根据替代用户名查找
				WTUser user2 = getUserByName(userCode);
				if (user1 == null && user2 == null) {
					//buffer.append("请输入正确的工号！");
					//creator = (wt.org.WTUser) wt.session.SessionHelper.manager.getPrincipal();
					ebuffer.append("NoEmail");
				} else if (user1 != null) {
					String email = user1.getEMail();// 电子邮件
					if ("".equals(email) || email == null) {
						buffer.append("该用户下未查找到邮箱！");
					}
					ebuffer.append(email);
					creator = user1;
				} else if (user2 != null) {
					String email = user2.getEMail();// 电子邮件
					if ("".equals(email) || email == null) {
						buffer.append("该用户下未查找到邮箱！");
					}
					ebuffer.append(email);
					creator = user2;
				}
			} else {
				//buffer.append("请输入正确的工号！");
				//creator = (wt.org.WTUser) wt.session.SessionHelper.manager.getPrincipal();
				ebuffer.append("NoEmail");
			}

			// 获取要创建的所有成品number和name
			JSONArray array = new JSONArray(parts);
			for (int i = 0; i < array.length(); i++) {
				JSONObject p = array.getJSONObject(i);
				num = p.getString("model").trim();
				number = num.toUpperCase();
				if (StringUtil.isNullOrEmpty(number)) {
					// buffer.append("成品编号不能为空！");
					continue;
				}

				name = p.getString("type");
				if (StringUtil.isNullOrEmpty(name)) {
					buffer.append("成品名称不能为空！");
					continue;
				}

				// 成品是否存在
				// master表和part表中的数据不对应
				WTPartMaster temp1 = CoreUtil.getWTPartMasterByNumber(number);
				WTPart temp = GenericUtil.getWTPart(number, "");
				if ((null != temp1) || (null != temp)) {
					repartPartBuf.append("成品编号" + num + "已存在！");
				}

				table.put(number, name);
			}

			// emessage = buffer.toString();

		} catch (WTException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.info(e);
			log.info("================" + e);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.info(e);
			log.info("================" + e);
		}

		return table;
	}

	/**
	 * 调用ERDP接口
	 * 
	 * @param erdpArr
	 * @throws Exception
	 */
	public static void sendToErdp(JSONArray erdpArr) throws Exception {
		String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma" + File.separator + "cfg"
				+ File.separator + "TianmaPro.properties";

		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String erdpUrl = ut.getValueByKey("erdp.url");
		erdpUrl = erdpUrl + "/tmrdp/v1/linkedproduct/windchill/batch/create";
		String s_utf8 = new String(erdpArr.toString().getBytes(), "UTF-8");
		String key = ut.getValueByKey("cookie.key");
		String value = ut.getValueByKey("erdp.value");
		String result = sendJsonDataByPost(erdpUrl, s_utf8, value, key);

		JSONObject jsonO1 = new JSONObject(result);
		Boolean b = (Boolean) jsonO1.get("success");
		if (true == b) {
			JSONObject jsonO2 = (JSONObject) jsonO1.get("res");
			JSONArray arr = jsonO2.getJSONArray("data");
			for (int k = 0; k < arr.length(); k++) {
				JSONObject obj1 = (JSONObject) arr.get(k);
				String projectManager = obj1.getString("projectManager");
				String projectNumber = obj1.getString("projectNumber");
				String projectName = obj1.getString("projectName");
				String productNumber = obj1.getString("productNumber");
				String viewName = "Design";
				String synchronousPartMessage = PLMSynchronousPartService.synchronousPartMessage(productNumber,
						viewName, projectNumber, projectName, projectManager);
				log.info("===synchronousPartMessage===：" + synchronousPartMessage);
			}

		}
		String erdpMessage = (String) jsonO1.get("message");
		log.info("===erdpMessage===:" + erdpMessage);

	}

	public static String sendJsonDataByPost(String url, String jsonData, String value, String key)
			throws ClientProtocolException, IOException {
		DefaultHttpClient client = null;
		if (client == null) {
			// Create HttpClient Object
			client = new DefaultHttpClient();
			enableSSL(client);
		}
		client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
		client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
		client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
		client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

		// log.info(HTTP.UTF_8);
		// Send data by post method in HTTP protocol,use HttpPost instead of
		// PostMethod which was occurred in former version
		// log.info(url);
		HttpPost post = new HttpPost(url);
		post.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
		post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
		post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
		post.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

		// Construct a string entity
		/*
		 * StringEntity entity = new StringEntity(getUTF8XMLString(jsonData), "UTF-8");
		 */
		StringEntity entity = new StringEntity(jsonData, "UTF-8");
		entity.setContentType("application/json;charset=UTF-8");
		entity.setContentEncoding("UTF-8");
		// Set XML entity
		post.setEntity(entity);
		// Set content type of request header
		post.setHeader("Content-Type", "application/json;charset=UTF-8");
		post.setHeader(key, value);
		// Execute request and get the response
		HttpResponse response = client.execute(post);
		HttpEntity entityRep = response.getEntity();
		String strrep = "";
		if (entityRep != null) {
			strrep = EntityUtils.toString(response.getEntity());
			// Do not need the rest
			post.abort();
		}
		// Response Header - StatusLine - status code
		// statusCode = response.getStatusLine().getStatusCode();
		return strrep;
	}

	/**
	 * 访问https的网站
	 * 
	 * @param httpclient
	 */
	public static void enableSSL(DefaultHttpClient httpclient) {
		// 调用ssl
		// String res = "";
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpclient.getConnectionManager().getSchemeRegistry().register(https);
		} catch (Exception e) {
			// res = "fail";
			//e.printStackTrace();
			log.info(e);
			log.info("================" + e);
		}
		// return res;
	}

	/**
	 * 重写验证方法，取消检测ssl
	 */
	public static TrustManager truseAllManager = new X509TrustManager() {
		public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};

	/**
	 * 根据用户名或者替代用户名获得用户
	 * 
	 * @param name
	 * @return
	 */
	private static WTUser getUserByName(String name) {
		WTUser user = null;
		try {
			String[] defaultService = OrganizationServicesHelper.manager.getDirectoryServiceNames();
			DirectoryContextProvider dcp = OrganizationServicesHelper.manager
					.newDirectoryContextProvider(defaultService, new String[] { "subtree" });
			Enumeration eee = OrganizationServicesHelper.manager.findLikeUsers("name", name,
					new GenericDirectoryContextProvider(defaultService));
			if (eee.hasMoreElements())
				user = (WTUser) eee.nextElement();
		} catch (WTException wte) {
			//wte.printStackTrace();
			log.info(wte);
			log.info("================" + wte);
		}
		return user;
	}

}
